package com.avcdata;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        List<String> names = getAllFile("/Users/hwangchan/IdeaProjects/json-to-obj/src/main/java/com/avcdata/read", false);
        for (String name : names) {
            List<String> lines = Files.readAllLines(Paths.get(name), StandardCharsets.UTF_8);
            StringBuilder sb = new StringBuilder();
            for (String line : lines) {
                sb.append(line);
            }
            String fromFile = sb.toString();
            Item item = JSONObject.parseObject(fromFile, Item.class);
            Path write_path = Paths.get(name.replace("read", "write"));
            if (Files.exists(write_path)) {
                Files.delete(write_path);
            }
            Files.createFile(write_path);
            List<Feature> features = item.getFeatures();
            for (Feature feature : features) {
                String childName = feature.getProperties().getName();
                String ff = JSONObject.toJSONString(feature);
                Files.write(write_path, (childName + "\t" + ff + "\n").getBytes(), StandardOpenOption.APPEND);
            }
        }

    }


    public static List<String> getAllFile(String directoryPath, boolean isAddDirectory) {
        List<String> list = new ArrayList<>();
        File baseFile = new File(directoryPath);
        if (baseFile.isFile() || !baseFile.exists()) {
            return list;
        }
        File[] files = baseFile.listFiles();
        assert files != null;
        for (File file : files) {
            if (file.isDirectory()) {
                if (isAddDirectory) {
                    list.add(file.getAbsolutePath());
                }
                list.addAll(getAllFile(file.getAbsolutePath(), isAddDirectory));
            } else {
                list.add(file.getAbsolutePath());
            }
        }
        return list;
    }
}
